package service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import controllers.ValidationUtil;

import models.Administrator;
import models.BaseEntity.PeopleType;
import models.BaseEntity.Status;
import models.Commodity.ChangeQuantityWay;
import models.Commodity.OnSaleStatus;
import models.Commodity;
import models.PricedCommodity;
import models.ShoppingCar;
import models.User;
import models.UserGroup;
import models.UserGroup.UserGroupType;
import play.data.validation.Valid;
import play.db.jpa.JPA;

public class CommoditiesService {
	/**
	 * 把商品放到购物车中。
	 * @param commodity 商品
	 * @param quantity 购买数量
	 * @param remark 说明
	 * @param buyer 购买者
	 * @param editor 操作人
	 */
	public static void addCommodity2ShoppingCar(Commodity commodity, 
			int quantity, String remark, User buyer, User editor) {
		ShoppingCar shoppingCar = new ShoppingCar();
		shoppingCar.quantity = Long.valueOf(quantity);
		shoppingCar.commodity = commodity;
		shoppingCar.remark = remark;
		shoppingCar.user = buyer;
		shoppingCar.setCreator(editor);
		shoppingCar.resetModifier(editor);
		shoppingCar.save();
	}

	/**
	 * 给购物车里的指定项增加购买数量。
	 * @param id ShoppingCar Item 的Id
	 * @param quantity 要增加的数量
	 * @param editor 操作者
	 * @throws Exception 
	 */
	public synchronized static void addQuantity2ShoppingCar(long id, int quantity, User editor) throws Exception {
		ShoppingCar shoppingCar = ShoppingCar.findById(id);
		if(shoppingCar == null) throw new Exception("购物车项（id:"+ id +"）已经被删除，请刷新列表。");
		shoppingCar.quantity += quantity;
		shoppingCar.resetModifier(editor);
		shoppingCar.save();
	}
	
	/**
	 * 购买商品，把商品放到购物车中。
	 * @param commodityId
	 * @param quantity
	 * @param remark
	 * @param buyer
	 * @param editor
	 * @throws Exception 
	 */
	public static void buy(long commodityId, int quantity, 
			String remark, User buyer, User editor) throws Exception {
		Commodity commodity = Commodity.findById(commodityId);
		if(commodity == null){
			String errMsg = "商品（id:"+ commodityId +"）已经被删除。";
			throw new Exception(errMsg);
		}
		ShoppingCar shoppingCar = ShoppingCar.find("user.id = ? and commodity.id = ?",
				buyer.id, commodity.id).first();
		if(shoppingCar != null) {
			CommoditiesService.addQuantity2ShoppingCar(shoppingCar.id,
					quantity, editor);
		} else {
			CommoditiesService.addCommodity2ShoppingCar(commodity,
					quantity, null, buyer, editor);
		}
	}
	
	/**
	 * 根据用户和用户组查询并设置商品的价格。
	 * 
	 * @param commodity 商品
	 * @param user 用户，可为空。
	 */
	public static void setCommodityPriceByUser(Commodity commodity, User user) {
		if(commodity == null) return;
		List<PricedCommodity> prices;
		//1  为没有登录的用户查找价格。
		if(user == null) {
			prices = PricedCommodity.find(
					"commodity.id=? and group.isDefault = ? and status != ? and group.status != ?",
					commodity.id, true, Status.DISABLED, Status.DISABLED).fetch();
			commodity.price = prices.get(0).price;
			return;
		}
		//2  查找商品所有对应价格
		prices = PricedCommodity.find("commodity.id=? and status != ?", 
				commodity.id, Status.DISABLED).fetch();
		//3 查找用户对应的所有组
		List<UserGroup> groups = JPA.em().createQuery(
				"select elements(u.groups) from User as u where u.id="+user.id, 
				UserGroup.class).getResultList(); 
		
		//4 把用户组按持久类型与暂时类型分开。
		UserGroup inherenceGroup = new UserGroup();
		List<UserGroup> transientGroup = new ArrayList<UserGroup>();
		for(UserGroup group : groups) {
			if(group.status != Status.DISABLED) {
				if(group.type == UserGroupType.INHERENCE) {
					if(group.priority > inherenceGroup.priority)
						inherenceGroup = group;
				} else {
					transientGroup.add(group);
				}
			}
		}
		
		//5 价格匹配。
		//5.1 查看有否单独指定价格，有则直接用此价格
		for(PricedCommodity price : prices) {
			for(UserGroup group : transientGroup) {
				if(price.group.id == group.id) {
					commodity.price = price.price;
					return;
				}
			}
		}
		//5.2 查找对应的用户组价格。
		if(inherenceGroup.isDefault == true) {
			prices = PricedCommodity.find(
					"commodity.id=? and group.isDefault = ? and status != ? and group.status != ?",
					commodity.id, true, Status.DISABLED, Status.DISABLED).fetch();
			commodity.price = prices.get(0).price;
			return;
		} else {
			List<PricedCommodity> inherenceGroupPrices = PricedCommodity.find(
					"commodity.id=? and group.priority <= ? and group.type=? and status!=? order by group.priority desc", 
					commodity.id, inherenceGroup.priority, UserGroupType.INHERENCE, Status.DISABLED).fetch();
			if(!ValidationUtil.isEmpty(inherenceGroupPrices))
				commodity.price = inherenceGroupPrices.get(0).price;
		}
	}
	
	/**
	 * 根据用户和用户组查询并设置商品的价格。
	 * @param commodity 商品列表
	 * @param user 用户，可为空。
	 */
	public static void setCommodityPriceByUser(List<Commodity> commoditis, User user) {
		if(commoditis != null ) {
			for(Commodity commodity : commoditis) {
				setCommodityPriceByUser(commodity, user);
			}
		}
	}
	
	/**
	 * 修改商品数量。
	 * @param id
	 * @param onSaleStatus
	 * @param changeQuantityWay
	 * @param quantityLeft
	 */
	public synchronized static void changeCommodityLeft(long id, OnSaleStatus onSaleStatus,
			ChangeQuantityWay changeQuantityWay, long quantityLeft, Administrator admin) {
		Commodity oricommodity = Commodity.findById(id);
		System.out.println(oricommodity.quantityLeft);
		if(oricommodity != null) {
			if(changeQuantityWay == changeQuantityWay.ADD) {
				oricommodity.quantityLeft = oricommodity.quantityLeft + quantityLeft;
			} else if(changeQuantityWay == changeQuantityWay.MINUS) {
				oricommodity.quantityLeft = (oricommodity.quantityLeft - quantityLeft);
				if(oricommodity.quantityLeft < 0) {
					oricommodity.quantityLeft = 0;
				}
			} else {
				oricommodity.quantityLeft = quantityLeft;
			}
			oricommodity.onSaleStatus = onSaleStatus;
			oricommodity.resetModifier(admin);
			oricommodity.save();
		}
	}
}
